﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace SimpleSocxs
{
    public class UrlRewrite : IHttpModule
    {        
        void OnBeginRequest(object sender, EventArgs args)
        {
            var http_context = HttpContext.Current;
            var request_url = http_context.Request.Url;
            var absolute_path = request_url.AbsolutePath;
            
            var match = Regex.Match(absolute_path, @"^/users/ (?<name>[^/]+) ((?<asset>/assets/.*)|(?<path>/.*))?", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
            if (match.Success)
            {                
                HttpContext.Current.Items["original_path"] = request_url;

                var username = match.Groups["name"].Value;
                var path = match.Groups["path"].Value;
                var asset = match.Groups["asset"].Value;
                if (string.IsNullOrEmpty(asset) == false)
                    http_context.RewritePath("~/users/" + username + asset);
                else
                    http_context.RewritePath("~/userpage.aspx?user="+username+"&path=" + path);
            }
        }        

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
        }                

        public void Dispose()
        {
            
        }        
    }
}